<template>
  <div class="map-top-filter flex pointer-auto">
    <div class="full-screen-btn mr-5" @click="operateFullScreen(!fullScreen)">
      <i v-if="!fullScreen" class="iconfont icon-AFShome-hide" />
      <i v-else class="iconfont icon-AFShome-open" />
    </div>
    <el-select v-model="filterType" class="mr-5" style="width: 1.375rem">
      <el-option value="REGIONS" :label="$t('FILTER_BY_REGION')" />
      <el-option value="CABLE" :label="$t('FILTER_BY_FIBER')" />
    </el-select>
    <div ref="showPanel" class="region-tree">
      <div v-if="filterType === 'REGIONS'" class="flex">
        <div class="relative filter-input mr-5">
          <div class="flex align-center regionListLabel" @click.self="showTree(true)">
            <div v-if="selectRegions.length > 0" class="flex align-center">
              <div
                v-for="(item, index) in selectRegions"
                :key="index"
                class="regionLabel"
                @click="showTree(true)"
              >
                <span class="regiontext flex align-center">
                  {{ item.regionName }}
                </span>
              </div>
              <span v-if="regNum > 0" class="regNum">+{{ regNum }}</span>
              <i class="el-icon-close clearRegion" @click.self="clearRegion" />
            </div>
            <span v-else class="placeholder">{{ $t('SELECT_REGION') }}</span>
          </div>
          <div class="visible-btn flex align-center">
            <i v-if="treeHeight" class="el-icon-arrow-up" @click="showTree(false)" />
            <i v-else class="el-icon-arrow-down" @click="showTree(true)" />
          </div>
        </div>
        <el-select
          v-model="checkedStation"
          class="station-select"
          multiple
          collapse-tags
          filterable
          clearable
          :placeholder="$t('IN_KEYWORD')"
          :reserve-keyword="true"
          style="width: 180px"
          @visible-change="showTree(false)"
        >
          <el-option
            v-for="item in stationList"
            :key="item.regionId"
            :value="item.regionId"
            :label="item.regionName"
          />
        </el-select>
        <el-button icon="el-icon-search" @click="getStatistics(true)" />
      </div>
      <div v-else class="flex">
        <div class="relative filter-input">
          <div class="flex align-center regionListLabel" @click.self="showTree(true)">
            <div v-if="selectRegions.length > 0" class="flex align-center">
              <div
                v-for="(item, index) in selectRegions"
                :key="index"
                class="regionLabel"
                @click="showTree(true)"
              >
                <span class="regiontext flex align-center">
                  {{ item.regionName }}
                </span>
              </div>
              <span v-if="regNum > 0" class="regNum">+{{ regNum }}</span>
              <i class="el-icon-close clearRegion" @click.self="clearRegion" />
            </div>
            <span v-else class="placeholder">{{ $t('SELECT_CABLE_LEVEL') }}</span>
          </div>
          <div class="visible-btn flex align-center">
            <i v-if="treeHeight" class="el-icon-arrow-up" @click="showTree(false)" />
            <i v-else class="el-icon-arrow-down" @click="showTree(true)" />
          </div>
        </div>
        <el-button icon="el-icon-search" @click="getStatistics(true)" />
      </div>
      <div :style="{ height: treeHeight + 'px' }" class="filter-tree">
        <div class="p-5 pl-10 pb-0">
          <el-checkbox
            v-model="selectedAll"
            class="font-weight-bolder"
            @change="selectedAllChange"
          >{{ $t('ALL_' + filterType) }}</el-checkbox>
        </div>
        <el-tree
          ref="filterTree"
          :style="{ height: treeHeight - 30 + 'px' }"
          node-key="regionId"
          show-checkbox
          check-strictly
          :data="treeData"
          :props="defaultProps"
          :filter-node-method="filterNode"
          @check="checkedChange"
        />
      </div>
    </div>
  </div>
</template>
<script>
  import { mapGetters, mapMutations } from 'vuex'
  export default {
    data() {
      return {
        filterType: 'REGIONS',
        filterText: '',
        treeHeight: 0,
        defaultProps: {
          id: 'regionId',
          children: 'children',
          label: 'label'
        },
        checkedKeys: [],
        stationList: [],
        checkedStation: [],
        checkedRegion: [],
        selectedAll: false
      }
    },
    computed: {
      ...mapGetters([
        'baseRegionList',
        'onlyRegionTree',
        'mapType',
        'fullScreen',
        'customDictList'
      ]),
      dictCableLevelList() {
        return this.customDictList.filter(i => i.type === 'CABLE_LEVEL')
      },
      regNum() {
        return this.selectedAll ? 0 : this.checkedRegion.length - 2
      },
      selectRegions() {
        const allRegion = {
          regionName: this.$t('ALL_' + this.filterType)
        }
        return this.selectedAll ? [allRegion] : this.checkedRegion.slice(0, 2)
      },
      treeData() {
        return this.filterType === 'REGIONS'
          ? this.onlyRegionTree
          : this.dictCableLevelList.map(i => {
            return {
              ...i,
              level: 1,
              regionId: i.value,
              regionName: i.label
            }
          })
      },
      allStationList() {
        return this.baseRegionList.filter(i => i.regionType === 'STATION')
      }
    },
    watch: {
      filterType() {
        this.selectedAllChange(true)
      },
      baseRegionList() {
        this.init()
      },
      onlyRegionTree() {
        this.init()
      }
    },
    created() {
      this.init()
    },
    beforeDestroy() {
      this.dataTimer && clearTimeout(this.dataTimer)
      this.dataTimer = null
    },
    mounted() {
      document.addEventListener('click', (event) => {
        if (this.$refs.showPanel) {
          const isSelf = this.$refs.showPanel.contains(event.target)
          if (!isSelf) {
            this.showTree(false)
          }
        }
      }, false)
    },
    methods: {
      ...mapMutations(['setCableLevelSelected']),
      init() {
        this.$nextTick(() => {
          this.dataTimer && clearTimeout(this.dataTimer)
          this.dataTimer = null
          this.dataTimer = setTimeout(() => {
            this.checkedRegion = this.treeData
            this.getStationList()
            this.getStatistics()
          }, 1000)
        })
      },
      clear() {
        this.checkedRegion = this.treeData
        this.getStationList()
        this.checkedStation = []
      },
      filterNode(value, data) {
        if (!value) return true
        return data.label.indexOf(value) !== -1
      },
      clearRegion() {
        // console.log('clearRegion')
        this.checkedRegion = []
        this.getStationList()
      },
      checkedChange(data, checkedData) {
        this.checkedRegion = checkedData.checkedNodes.some(i => i.level !== data.level)
          ? [data]
          : checkedData.checkedNodes
        this.getStationList()
      },
      selectedAllChange(val) {
        this.checkedRegion = val ? this.treeData : []
        this.getStationList()
      },
      getStationList() {
        // console.log('getStationList', this.checkedRegion)
        const firstData = this.checkedRegion[0]
        this.selectedAll = !!(
          firstData &&
          firstData.level === 1 &&
          this.checkedRegion.length === this.treeData.length
        )
        const checkedRegionIds = this.checkedRegion.map(i => i.regionId)
        this.$refs.filterTree.setCheckedKeys(checkedRegionIds)
        if (this.checkedRegion.length === 0) {
          this.stationList = this.allStationList
        } else {
          this.stationList = this.allStationList.filter(i =>
            i.parentIds.some(j => checkedRegionIds.includes(j))
          )
        }
        const oldVal = this.checkedStation
        this.checkedStation = oldVal.filter(i => this.stationList.some(j => j.regionId === i))

        // console.log(this.stationList)
      },
      showTree(type) {
        // console.log('this.checkedKeys', this.checkedKeys)
        this.treeHeight = type ? 260 : 0
      },
      operateFullScreen(type) {
        this.showTree(false)
        this.$emit('operateFullScreen', type)
      },
      getStatistics(needFitView = false) {
        needFitView && this.$store.commit('setNeedFitView', needFitView)
        this.setCableLevelSelected(this.dictCableLevelList.map(i => i.code)) // 重置cableLevelSelected里的光缆等级
        this.showTree(false)
        let checkedRegions = []
        let showRegionIds = []
        const checkedKeys = this.checkedRegion.map(i => i.regionId)
        if (this.checkedStation.length) {
          showRegionIds = this.checkedStation
          checkedRegions = this.allStationList.filter(i => showRegionIds.includes(i.regionId))
        } else {
          if (checkedKeys.length === 0 || this.selectedAll) {
            showRegionIds = this.onlyRegionTree.map(i => i.regionId)
            checkedRegions = this.baseRegionList.filter(
              i => i.regionType === 'STATION' || i.parentId === '0'
            )
            if (this.filterType === 'CABLE') {
              this.setCableLevelSelected(this.dictCableLevelList.map(i => i.code))
            }
          } else {
            checkedRegions = this.checkedRegion
            showRegionIds = checkedRegions.map(j => j.regionId)
            if (this.filterType === 'CABLE') {
              this.setCableLevelSelected(showRegionIds)
            }
          }
        }
        this.$emit('regionChanged', {
          checkedNodes: checkedRegions,
          showRegionIds: showRegionIds,
          checkedStation: this.checkedStation,
          stationSelected: !!this.checkedStation.length,
          selectedAll: checkedKeys.length === 0 || this.selectedAll,
          filterType: this.filterType
        })
      }
    }
  }
</script>
<style lang="scss">
  @import '@/assets/css/mixin.module.scss';
  .map-top-filter {
    z-index: 1;

    .full-screen-btn {
      width: 0.25rem;
      min-height: 28px;
      cursor: pointer;
      border-radius: 0 4px 4px 0;
      display: flex;
      align-items: center;
      justify-content: center;
      @include themeify {
        color: themed('pageActiveFontColor');
        background: themed('mainColor');
      }

      .iconfont {
        font-size: 12px;
      }
    }

    .region-tree {
      z-index: 2;

      .filter-input {
        width: 240px;
        .regionListLabel {
          height: 28px;
          min-height: 28px;
          line-height: 28px;
          border-radius: 4px;
          padding: 3px 10px;
          box-sizing: border-box;
          @include themeify {
            color: themed('inputActiveFontColor');
            background: themed('inputBgColor');
            border: 1px solid themed('inputBorderColor');
          }
          .regionLabel {
            padding: 0 5px;
            margin-right: 2px;
            box-sizing: border-box;
            border-radius: 2px;
            @include themeify {
              color: themed('inputActiveFontColor');
              background: themed('multiBgColor');
            }
          }
          .regiontext {
            height: 20px;
            max-width: 80px;
            // white-space: nowrap;
            white-space: pre;
            overflow: hidden;
            text-overflow: ellipsis;
            font-size: 12px;
          }
          .regNum,
          .placeholder {
            font-size: 12px;
          }
          .clearRegion {
            position: absolute;
            right: 30px;
            top: 8px;
            font-size: 12px;
            cursor: pointer;
            display: none;
          }
          &:hover .clearRegion {
            display: block;
          }
        }
        .el-input__inner {
          padding-right: 40px;
          @include themeify {
            color: themed('textColor');
            background: themed('homeGridbg');
          }
        }
        .el-input__suffix {
          transform: translateX(-15px) !important;
        }

        .el-input-group__append {
          padding: 0;
          font-size: 14px;

          .el-button {
            padding: 0 10px;
            margin: 0;
            background: transparent;
          }
        }

        .visible-btn {
          height: 28px;
          position: absolute;
          top: 0;
          right: 10px;
          cursor: pointer;
          font-size:12px;
          @include themeify {
            color: themed('homeAxisText');
          }
        }
      }

      .station-select {
        width: 130px;
        .el-input__inner {
          border-radius: 4px 0 0 4px;
          border-right: 0;
        }
      }
      .el-button--mini {
        border-radius: 0 3px 3px 0;
      }
    }
    .filter-tree {
      position: absolute;
      top: 30px;
      left: auto;
      width: 240px;
      margin: 5px 0 0 0;
      border-radius: 5px;
      transition: all 0.3s;
      box-sizing: content-box;
      overflow: hidden auto;
      z-index: 10;
      @include themeify {
        background: themed('homeTooltipBg');
        // border: 1px solid themed('homeTooltipBorderColor');
        box-shadow: 0px 0px 10px 0px themed('homeTooltipShadow');
      }
      .el-tree-node__content {
        height: auto !important;
        line-height: 1.6 !important;
        align-items: baseline;
      }
      .el-tree-node__label {
        /* white-space: normal; */
        white-space: pre-wrap;
        word-break: break-all;
      }
    }
  }
</style>
